<?php

namespace app\common\model\marketing;

use addons\xyb\XypHelper;
use app\common\model\Config;
use app\common\model\marketing\label\Category;
use app\common\model\marketing\label\Label;
use app\common\model\marketing\label\Level;
use think\Db;
use think\Model;


class Association extends Model
{

    // 表名
    protected $name = 'association';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    public static $grant_method_list = [
        1 => '全部',
        2 => '指定区域',
        3 => '指定用户',
    ];

    public static $examine_method_list = [
        1 => ['color'=>'purple','label'=>'系统审核'],
        2 => ['color'=>'primary','label'=>'人工审核'],
    ];


    public static $grant_status_list = [
        1 => ['color'=>'green','label'=>'进行中'],
        2 => ['color'=>'gold','label'=>'已结束'],
        3 => ['color'=>'orange','label'=>'已下架'],
    ];

    protected $append = [
        'involved_users',
        'activity_jobs',
        'grant_status_text',
        'grant_method_text',
        'start_date_text',
        'create_date',
        'label_name',
        'examine_method_text',
        'category_name'
    ];

    public function getExamineMethodTextAttr($value, $data){
        if(!isset($data['examine_method']) || !$data['examine_method']){
            return '';
        }
        return isset(self::$examine_method_list[ $data['examine_method']]) ? self::$examine_method_list[ $data['examine_method']] : '';
    }

    public function getCategoryNameAttr($value, $data){
        if(!isset($data['category_id']) || !$data['category_id']){
            return '';
        }
        if(!$category_id = XypHelper::formatJsonStringToArray($data['category_id'])){
            return '';
        }
        $lists = Category::where('id', 'in', $category_id)->column('name');
        if($label_id = end($category_id)){
            if($label_name = Label::where('id', $label_id)->value('name')){
                array_push($lists, $label_name);
            }
        }
        return implode(' / ', $lists);

    }

    public function getGrantStatusTextAttr($value, $data){
        if(!isset($data['grant_status']) || !$data['grant_status']){
            return '';
        }
        return isset(self::$grant_status_list[ $data['grant_status']]) ? self::$grant_status_list[ $data['grant_status']] : '';
    }


    public function getActivityJobsAttr($value, $data){
      if(isset($data['id']) && $data['id']){
          return AssociationUsers::where('association_id', $data['id'])->count('id');
      } elseif (isset($data['value']) && $data['value']){
          return AssociationUsers::where('association_id', $data['value'])->count('id');
      }
      return 0;
    }
    public function getInvolvedUsersAttr($value, $data){
        if(isset($data['association_id']) && $data['association_id']){
            return AssociationUsers::where('association_id', $data['association_id'])->count('id');
        } else {
            return 0;
        }
        //return Association::where('id', $data['association_id'])->value('name');
    }

    public function getGrantMethodTextAttr($value, $data){
        if(isset($data['grant_method']) && $data['grant_method']){
            $value = $value ? $value : (isset($data['grant_method']) ? $data['grant_method'] : '');
            return isset(self::$grant_method_list[$value]) ? self::$grant_method_list[$value] : '';
        }else {
            return '';
        }
    }
    public function getStartDateTextAttr($value, $data){
        if(isset($data['start_time']) && strlen($data['start_time']) <= 11){
            return date('Y-m-d H:i', $data['start_time']) .' ~ '. date('Y-m-d H:i', $data['end_time']);
        } else {
            return '';
        }
    }

    public function getCreateDateAttr($value, $data){
        if(isset($data['createtime']) && $data['createtime']) {
            return date('Y-m-d H:i', $data['createtime']);
        }else {
            return '';
        }
    }

    public function getLabelNameAttr($value, $data){
        if(isset($data['label_id']) && $data['label_id']) {
            return Label::where('id', $data['label_id'])->value('name');
        }else {
            return '';
        }
    }

    public static function getDailyAdminLists(){
        $name = request()->param('name', '');
        $category_id = request()->param('category_id/a', '');
        $deadline = request()->param('deadline/a');
        $examine_method = request()->param('examine_method');
        $grant_status = request()->param('grant_status');
        $field = '';
        $query = self::field($field)->where('activity_method', 2);
        if ($name) {
            $query->where('name', 'like', "%{$name}%");
        }
        if($category_id){
            $query->where(function ($query)use ($category_id){
                foreach ($category_id as $k => $v){
                    $query->where('category_id', 'like', "%{$v}%");
                }
            });
        }
        if ($deadline_arr = XypHelper::stringToArray($deadline)) {
            $query->where('start_time','>',  XypHelper::getTimestamp($deadline_arr[0]))
                ->where('end_time','<',  XypHelper::getTimestamp($deadline_arr[1]));
        }
        if ($examine_method) {
            $query->where('examine_method', $examine_method);
        }
        if ($grant_status) {
            $query->where('grant_status', $grant_status);
        }
        return $query->order('id desc')->paginate(10);
    }

    public static function getAdminLists()
    {
        $keyword = request()->param('keyword', '');
        $deadline = request()->param('deadline/a');
        $grant_status = request()->param('grant_status/a');
        $field = '';
        $query = self::field($field);
        if ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('id', 'like', "%{$keyword}%")
                    ->whereOr('name', 'like', "%{$keyword}%")
                    ->whereOr('describe', 'like', "%{$keyword}%");
            });
        }
        if ($deadline_arr = XypHelper::stringToArray($deadline)) {
            $query->where('start_time','>',  XypHelper::getTimestamp($deadline_arr[0]))
                ->where('end_time','<',  XypHelper::getTimestamp($deadline_arr[1]));
        }
        if ($grant_status = XypHelper::stringToArray($grant_status)) {
            $query->whereIn('grant_status', $grant_status);
        }
        return $query->order('id desc')->paginate(10);
    }

    public static function getAssociationJobsDetails($association_id){
        $association = self::field('id,name,start_time,end_time,grant_method,grant_agent_id,label_id')
            ->where('id', $association_id)->find();
        $jobs_lists = AssociationJobs::field('id,name,start_time,end_time,activity_method,involved_days,execute_days,label_level')
            ->where('association_id', $association_id)->order('id asc')->select();
        $association->jobs = $jobs_lists;
        if($jobs_lists){
            $association->start_date_time = (end($jobs_lists)->end_time) + 86400;
        } else {
            $association->start_date_time = $association->start_time;
        }
        $association->label_level = [];
        if($association->label_id){
            $label_level = Level::field('id as value,name as label,sign')->where('label_id', $association->label_id)->select();
            if($jobs_lists && $label_level){
                foreach ($label_level as $k=>$v){
                    $label_level[$k]['disabled'] = false;
                    foreach ($jobs_lists as $job_key => $job_val){
                        if($job_val->label_level && $job_val->label_level == $v->value){
                            $label_level[$k]['disabled'] = true;
                        }
                    }

                }
            }
            $association->label_level = $label_level;
        }
        return $association;
    }


    public static function submitDailyConfigSetupContent($id, $describe, $_action){
        if($_action == 'submit'){
            $res = Db::table('fa_config_setup')->where('id', $id)->update(['content' => $describe]);
        } else {
            $res = Db::table('fa_config_setup')->where('id', $id)->value('content');
        }
        return $res;
    }
}